package com.mo.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mo.entity.User;
import com.mo.service.IUserService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author mo
 * @since 2022-08-28
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    //根据up主的姓名，模糊查询该up主list。
    @GetMapping("/selectByName")
    public List<User> selectByName(String name) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like("name", name);
        return userService.list(wrapper);
    }

    @GetMapping("/selectOne")
    public User selectOne(Integer id) {
        return userService.getById(id);
    }

    @GetMapping("/users")
    public Map<String, Object> selectAllUsers(@RequestParam("page") int curPage,
                                              @RequestParam("per_page") int pageSize,
                                              @RequestParam(value = "id", required = false) Integer userId,
                                              String name,
                                              String phone) {
        IPage page = new Page(curPage, pageSize);
        QueryWrapper<User> wrapper = new QueryWrapper<User>();

        if (!ObjectUtils.isEmpty(userId)) {
            wrapper.eq("id", userId);
        }
        if (!StringUtils.isEmpty(name)) {
            wrapper.like("name", name);
        }
        if (!StringUtils.isEmpty(phone)) {
            wrapper.eq("phone", phone);
        }
        IPage resultPage = userService.page(page, wrapper);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("total_count", resultPage.getTotal());
        resultMap.put("items", resultPage.getRecords());
        return resultMap;
    }
}

